import kit from './kit.js' ;
const mobileReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
var emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
var amountReg = /^[0-9]{1}[0-9]*([.]{1}[0-9]{1,2})?$/;
var countReg = /^\d+$/;

function validIdCard(sIdCard){
	sIdCard= sIdCard.replace(/^\s+|\s+$/g,"");//去除字符串的前后空格，允许用户不小心输入前后空格
	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	if (!reg.test(sIdCard)) {//判断是否全为18或15位数字，最后一位可以是大小写字母X
		uni.showToast({
			title: '身份证号码须为18位或15位数字',
			icon : 'none'
		});
		return false;
	}else if (sIdCard.length==18) {
		if (CheckIdCard.province(sIdCard)&&CheckIdCard.brithday18(sIdCard)&&CheckIdCard.validate(sIdCard)) {
			
		}else{
			uni.showToast({
				title: '请输入有效的身份证号码',
				icon : 'none'
			});
			return false;
		};
	}else if (sIdCard.length==15) {
		if (CheckIdCard.province(sIdCard)&&CheckIdCard.brithday15(sIdCard)) {
		}else{
			uni.showToast({
				title: '请输入有效的身份证号码',
				icon : 'none'
			});
			return false;
		};
	};
	return true;
}

var CheckIdCard={
	//Wi 加权因子 Xi 余数0~10对应的校验码 Pi省份代码  
	Wi:[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],
	Xi:[1,0,"X",9,8,7,6,5,4,3,2],
	Pi:[11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91],

	//检验18位身份证号码出生日期是否有效  
	//parseFloat过滤前导零，年份必需大于等于1900且小于等于当前年份，用Date()对象判断日期是否有效。  
	brithday18:function(sIdCard){
		var year=parseFloat(sIdCard.substr(6,4));
		var month=parseFloat(sIdCard.substr(10,2));
		var day=parseFloat(sIdCard.substr(12,2));
		var checkDay=new Date(year,month-1,day);
		var nowDay=new Date();
		if (1900<=year && year<=nowDay.getFullYear() && month==(checkDay.getMonth()+1) && day==checkDay.getDate()) {
			return true;
		}
	},

	//检验15位身份证号码出生日期是否有效  
	brithday15:function(sIdCard){
		var year=parseFloat(sIdCard.substr(6,2));
		var month=parseFloat(sIdCard.substr(8,2));
		var day=parseFloat(sIdCard.substr(10,2));
		var checkDay=new Date(year,month-1,day);
		if (month==(checkDay.getMonth()+1) && day==checkDay.getDate()) {
			return true;
		}
	},

	//检验校验码是否有效  
	validate:function(sIdCard){
		var aIdCard=sIdCard.split("");
		var sum=0;
		for (var i = 0; i < CheckIdCard.Wi.length; i++) {
			sum+=CheckIdCard.Wi[i]*aIdCard[i]; //线性加权求和  
		}
		var index=sum%11;//求模，可能为0~10,可求对应的校验码是否于身份证的校验码匹配  
		if (CheckIdCard.Xi[index]==aIdCard[17].toUpperCase()) {
			return true;
		}
	},

	//检验输入的省份编码是否有效  
	province:function(sIdCard){
		var p2=sIdCard.substr(0,2);
		for (var i = 0; i < CheckIdCard.Pi.length; i++) {
			if(CheckIdCard.Pi[i]==p2){
				return true;
			}
		}
	}
};

function check(e){
	var data = e.detail.value ;
	var finalData = {} ;
	for( var key in data ){
		var value = data[key] ;
		var arr = key.split("|") ;
		var name = arr[0] ;
		finalData[name] = value ;
		
		if (arr.length == 1) {
			continue ;
		}
		
		var canEmpty = arr[arr.length-1] == "empty" ;
		if (canEmpty && !value) {
			continue ;
		}
		
		var znName = arr[1] ; //表单名称
		if (!value && !!znName) {
			var prefix = znName.indexOf("首图") > -1 ||znName.indexOf("图片") > -1 || znName.indexOf("附件") > -1 || znName.indexOf("文件") > -1 ? "请上传" : "请输入" ;
			uni.showToast({
				title: prefix + znName ,
				icon : 'none'
			});
			return false ;
		}
		
		
		
		if (arr.length == 2) {
			continue ;
		}
		
		var rule = arr[2] ;
		if ( rule.indexOf("~") > -1 ) { //区间标识
			var sectionArr = rule.split("~") ;
			var min = sectionArr[0] ;
			var max = sectionArr[1] ;
			if (value.length < min) {
				uni.showToast({
					title: znName + '最少' + min + "个字符",
					icon : 'none'
				});
				return false ;
			}
			if (value.length > max) {
				uni.showToast({
					title: znName + '最多' + max + "个字符",
					icon : 'none'
				});
				return false ;
			}
		}
		
		switch ( rule ){
			
			case 'mobile':
				if ( !mobileReg.test(value) ) { 
					uni.showToast({
						title: znName + '不正确',
						icon : 'none'
					});
					return false; 
				}
			break;
			
			case 'amount':
				if ( value != 0 && !amountReg.test(value) ) { 
					uni.showToast({
						title: znName + '不正确',
						icon : 'none'
					});
					return false; 
				}
			break;
			
			case 'count':
				if ( !countReg.test(value) ) { 
					uni.showToast({
						title: znName + '不正确',
						icon : 'none'
					});
					return false; 
				}
			break;
			
			case 'email':
				if (emailReg.test(value) == false ) {
					uni.showToast({
						title: znName + "不正确",
						icon : 'none'
					});
					return false ;
				}
			break;
			
			case 'idcard':
				if ( validIdCard(value) == false ) {
					return false ;
				}
			break;
		}
	}
	
	return finalData ;
}

function redirectTo( url , isRediret , backPath){
	if(backPath){
		kit.goBack(backPath);
		return false ;
	}
	if (isRediret) {
		uni.redirectTo({
			url: url
		});
	}else{
		uni.navigateTo({
			url: url 
		});
	}
}

function dealResult(res , dataset , success , fail ){
	uni.hideLoading();
	var needRediret = !dataset.rediret ;
	var rediretPath = dataset.rediret || kit.getPageRoute() ;
	var backPath = dataset.back ;
	if (res.state == "ok") {
		if (typeof success == "function") {
			success(res);
		}else{
			var alert = dataset.alert ;
			if (!!alert) {
				uni.showModal({
					title:'提示',
					content: alert == "true" || alert == true ? res.err : alert ,
					showCancel:false,
					confirmColor:"#5d83f7",
					success : function(e){
						redirectTo( rediretPath , needRediret , backPath);
					}
				});
			}else{
				redirectTo( rediretPath , needRediret , backPath);
			}
		}
	}else{
		if (typeof fail == "function") {
			fail(res);
		}else{
			uni.showToast({
				title: res.err ,
				icon : 'none'
			});
		}
	}
}

function submit( e , success , fail){
	var data = e.detail.value ;
	var dataset = e.currentTarget.dataset ;
	var confirmContent = dataset.confirm ;
	var finalData = check(e);
	if ( finalData == false) {
		return false ;
	}
	
	if (!!confirmContent) {
		uni.showModal({
			title:'提示',
			content: confirmContent ,
			showCancel:true,
			confirmColor:'#5d83f7',
			success : function(e){
				if (e.confirm) {
					submitData( dataset , finalData , success , fail);
				}
			}
		});
	}else{
		submitData( dataset , finalData , success , fail);
	}
}

function submitData( dataset , finalData , success , fail){
	uni.showLoading({
		title:"loading...",
		mask: true 
	});
	kit.reqesut( 
		dataset.action ,
		finalData, 
		function(res){ //ok
			dealResult(res , dataset , success , fail );
		} , 
		function(err){  //fail
			dealResult(err , dataset , success , fail );
		}, dataset.method );
}

function send(e , suc , err){
	var dataset = e.currentTarget.dataset ;
	var url = dataset.url ;
	var confirmContent = dataset.confirm ;
	var alertText = dataset.alert ;
	if (!!confirmContent) {
		uni.showModal({
			title:'提示',
			content: confirmContent ,
			showCancel:true,
			confirmColor:'#5d83f7',
			success : function(e){
				if (e.confirm) {
					kit.get(url , {} , function(res){
						dealResult(res , dataset , suc , err);
					},function(res){
						dealResult(res , dataset , suc , err);
					});
				}
			}
		});
	}else{
		kit.get(url , {} , function(res){
			dealResult(res , dataset , suc , err);
		},function(res){
			dealResult(res , dataset , suc , err);
		});
	}	
}

function deleteData(e){
	e.currentTarget.dataset.confirm = "删除后不可恢复，确认删除吗？";
	send(e); 
}
module.exports = {
	submit ,
	send ,
	deleteData ,
	check 
}